#!/bin/bash

java="java"

sedString="s/.*1\.\(.*\)\..*/\1/"
jVersion=$($java -version 2>&1 | grep version | awk '{ print $3 }' | sed $sedString)
if [[ $jVersion -lt 7 ]];
then
    echo "Wrong java version. Please use Java 7 or higher."
    exit 1
fi

# Linux readlink -f alternative for Mac OS X
function readlinkUniversal() {
    targetFile=$1

    cd `dirname $targetFile`
    targetFile=`basename $targetFile`

    # iterate down a (possible) chain of symlinks
    while [ -L "$targetFile" ]
    do
        targetFile=`readlink $targetFile`
        cd `dirname $targetFile`
        targetFile=`basename $targetFile`
    done

    # compute the canonicalized name by finding the physical path 
    # for the directory we're in and appending the target file.
    phys_dir=`pwd -P`
    result=$phys_dir/$targetFile
    echo $result
}

os=`uname`
delta=100

dir=""

case $os in
    Darwin)
        freeBlocks=$(vm_stat | grep free | awk '{ print $3 }' | sed 's/\.//')
        inactiveBlocks=$(vm_stat | grep inactive | awk '{ print $3 }' | sed 's/\.//')
        speculativeBlocks=$(vm_stat | grep speculative | awk '{ print $3 }' | sed 's/\.//')
        freeMb=$((($freeBlocks+$speculativeBlocks)*4096/1048576))
        inactiveMb=$(($inactiveBlocks*4096/1048576))
        maxMb=$((($freeMb+$inactiveMb-$delta)))
        dir=$(dirname "$(readlinkUniversal "$0")")
    ;;
    Linux)
        rFreeMb=$(free -m | grep Mem | awk '{ print $4 }')
        maxMb=$(($rFreeMb-$delta))
        dir="$(dirname "$(readlink -f "$0")")"
    ;;
    *)
       echo "Unknown OS."
       exit 1
    ;;
esac

migmap=${dir}/migmap

migmapArgs=()
javaArgs=()

needXmxXms=true
otherJar=""

while [[ $# > 0 ]]
do
    key="$1"
    shift
    case $key in
        -D*|-X*|-ea|-agentlib*)
            javaArgs+=(${key})

            case $key in
                -Xmx*|-Xms*)
                    needXmxXms=false
                    ;;
            esac

            ;;
        -jar|-V)
            otherJar="$1"
            shift
            ;;
        *)
            migmapArgs+=("${key}")
            ;;
    esac
done

if [[ ${needXmxXms} == true ]]
then
    targetXmx=12000

    if [[ $targetXmx -gt $maxMb ]];
    then
        targetXmx=$maxMb
    fi

    javaArgs+=("-Xmx${targetXmx}m")

    targetXms=$((${targetXmx}*2/3))

    if [[ $targetXms -lt 2000 ]];
    then
        targetXms=$targetXmx
    fi

    javaArgs+=("-Xms${targetXms}m")
fi

jar=""

if [[ -z "$otherJar" ]];
then
    for j in "$dir/../jar/migmap-1.0.3.jar" "$dir/migmap-1.0.3.jar" $(ls -d -1 $dir/target/* 2> /dev/null | grep distribution.jar)
    do
        if [[ -e "$j" ]];
        then
            jar=$j
            break
        fi
    done
else
    for j in $(ls -1 ${dir}/* | grep "migmap" | grep ".jar" | grep ${otherJar});
    do
        if [[ -e "$j" ]];
        then
            jar=$j
            break
        fi
    done
fi

if [[ "$jar" == "" ]];
then
    echo "No jar."
    exit 1
fi

$java -XX:+AggressiveOpts "${javaArgs[@]}" -jar $jar "${migmapArgs[@]}"
